import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioTestRoute extends StatefulWidget {
  const DioTestRoute({Key? key}) : super(key: key);

  @override
  _DioTestRouteState createState() => _DioTestRouteState();
}

class _DioTestRouteState extends State<DioTestRoute> {
  final Dio _dio = Dio();

  /*
   * 发起 GET 请求 :
   * var response = await _dio.get("/test?id=12&name=wendu")
   *
   * 对于GET请求我们可以将query参数通过对象来传递，上面的代码等同于：
   * var response = await _dio.get("/test",queryParameters:{"id":12,"name":"wendu"})
   *
   * 发起一个 POST 请求:
   * var response = await _dio.post("/test",data:{"id":12,"name":"wendu"})
   *
   * 发起多个并发请求:
   * var response = await Future.wait([_dio.post("/info"),_dio.get("/token")]);
   *
   * 下载文件:
   * var response = await _dio.download("https://www.google.com/",_savePath);
   *
   * 发送 FormData:
   * var formData = FormData.from({"name": "wendux","age": 25,});
   * var response = await _dio.post("/info", data: formData)
   *
   * 如果发送的数据是FormData，则dio会将请求header的contentType设为“multipart/form-data”。
   * 通过FormData上传多个文件:
   * FormData formData = FormData.from({
   *   "name": "wendux",
   *   "age": 25,
   *   "file1": UploadFileInfo(File("./upload.txt"), "upload1.txt"),
   *   "file2": UploadFileInfo(File("./upload.txt"), "upload2.txt"),
   *   // 支持文件数组上传
   *   "files": [
   *      UploadFileInfo(File("./example/upload.txt"), "upload.txt"),
   *      UploadFileInfo(File("./example/upload.txt"), "upload.txt")
   *   ]
   * });
   * var response = await dio.post("/info", data: formData)
   */

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dio Test'),
      ),
      body: Center(
        child: FutureBuilder<Response>(
          future: _dio.get("https://api.github.com/orgs/flutterchina/repos"),
          builder: (context, snapshot) {
            // 请求完成
            if (snapshot.connectionState == ConnectionState.done) {
              Response response = snapshot.data!;
              //发生错误
              if (snapshot.hasError) {
                return Text(snapshot.error.toString());
              } //请求成功，通过项目信息构建用于显示项目名称的ListView
              return ListView(
                children: response.data
                    .map<Widget>((e) => ListTile(title: Text(e["full_name"])))
                    .toList(),
              );
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
